package com.weijing.pretty_app.util

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.weijing.pretty_app.fragment.UserModel

object UserRepository {

    private val gson = Gson()

    private fun getUserList(): MutableList<UserModel> {
        val json = SPUtil.getString(KeyUtil.USER_LIST)
        return if (!json.isNullOrEmpty()) {
            val type = object : TypeToken<MutableList<UserModel>>() {}.type
            gson.fromJson(json, type)
        } else {
            mutableListOf()
        }
    }

    private fun saveUserList(list: List<UserModel>) {
        val json = gson.toJson(list)
        SPUtil.put(KeyUtil.USER_LIST, json)
    }

    fun addUser(name: String, gender: String, phone: String, address: String) {
        val list = getUserList()
        val lastId = SPUtil.getInt(KeyUtil.USER_ID) ?: 0
        val newId = lastId + 1

        val newUser = UserModel(
            id = newId, name = name, gender = gender, phone = phone, address = address
        )

        list.add(newUser)
        saveUserList(list)

        SPUtil.put(KeyUtil.USER_ID, newId) // 保存自增ID
    }

    fun updateUser(updatedUser: UserModel) {
        val list = getUserList()
        val index = list.indexOfFirst { it.id == updatedUser.id }
        if (index != -1) {
            list[index] = updatedUser
            saveUserList(list)
        }
    }

    fun deleteUserById(userId: Int) {
        val list = getUserList()
        list.removeAll { it.id == userId }
        saveUserList(list)
        // 注意：不修改 USER_ID_KEY，自增ID保持唯一性
    }

    fun getAllUsers(): List<UserModel> = getUserList()
}